package com.zenithmind.chat.controller;

import com.zenithmind.chat.pojo.dto.ChatMessageDTO;
import com.zenithmind.chat.pojo.entity.ChatMessage;
import com.zenithmind.chat.pojo.vo.ChatMessageVO;
import com.zenithmind.chat.service.ChatMessageService;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;

/**
 * 群组消息控制器 - 遵循单一职责原则
 * 只负责群组消息的HTTP接口处理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/chat/messages")
@RequiredArgsConstructor
@Validated
@Tag(name = "群组消息管理", description = "群组消息相关接口")
public class ChatMessageController {

    private final ChatMessageService chatMessageService;

    @PostMapping
    @Operation(summary = "发送消息", description = "发送群组消息")
    public Result<String> sendMessage(@Valid @RequestBody ChatMessageDTO dto) {
        String userId = UserContext.getUserId();
        String messageId = chatMessageService.sendMessage(dto, userId);
        return Result.success(messageId);
    }

    @GetMapping("/group/{groupId}")
    @Operation(summary = "查询群组消息", description = "分页查询指定群组的消息列表")
    public Result<PageResult<ChatMessageVO>> getGroupMessages(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize,
            @Parameter(description = "消息类型") @RequestParam(required = false) Integer messageType) {
        String userId = UserContext.getUserId();
        PageResult<ChatMessageVO> result = chatMessageService.getGroupMessages(groupId, pageNum, pageSize, messageType, userId);
        return Result.success(result);
    }

    @GetMapping("/session/{sessionId}")
    @Operation(summary = "查询会话消息", description = "分页查询指定会话的消息列表")
    public Result<List<ChatMessage>> getSessionMessages(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize) {
        List<ChatMessage> messages = chatMessageService.getMessagesBySessionId(sessionId, pageNum, pageSize);
        return Result.success(messages);
    }

    @GetMapping("/{messageId}")
    @Operation(summary = "查询消息详情", description = "根据消息ID查询消息详细信息")
    public Result<ChatMessageVO> getMessageById(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        String userId = UserContext.getUserId();
        ChatMessageVO message = chatMessageService.getMessageById(messageId, userId);
        return Result.success(message);
    }

    @PutMapping("/{messageId}")
    @Operation(summary = "编辑消息", description = "编辑已发送的消息")
    public Result<Boolean> editMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId,
            @Parameter(description = "新内容") @RequestParam @NotBlank String content) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageService.editMessage(messageId, content, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{messageId}")
    @Operation(summary = "撤回消息", description = "撤回已发送的消息")
    public Result<Boolean> recallMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageService.recallMessage(messageId, userId);
        return Result.success(result);
    }

    @PostMapping("/{messageId}/forward")
    @Operation(summary = "转发消息", description = "转发消息到其他群组或会话")
    public Result<Boolean> forwardMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId,
            @RequestBody @NotEmpty List<String> targetIds,
            @Parameter(description = "目标类型") @RequestParam @NotBlank String targetType) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageService.forwardMessage(messageId, targetIds, targetType, userId);
        return Result.success(result);
    }

    @PostMapping("/{messageId}/reply")
    @Operation(summary = "回复消息", description = "回复指定消息")
    public Result<String> replyMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId,
            @Valid @RequestBody ChatMessageDTO dto) {
        String userId = UserContext.getUserId();
        String replyMessageId = chatMessageService.replyMessage(messageId, dto, userId);
        return Result.success(replyMessageId);
    }

    @PostMapping("/{messageId}/like")
    @Operation(summary = "点赞消息", description = "给消息点赞")
    public Result<Boolean> likeMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageService.likeMessage(messageId, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{messageId}/like")
    @Operation(summary = "取消点赞", description = "取消对消息的点赞")
    public Result<Boolean> unlikeMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageService.unlikeMessage(messageId, userId);
        return Result.success(result);
    }

    @PostMapping("/{messageId}/pin")
    @Operation(summary = "置顶消息", description = "将消息置顶到群组")
    public Result<Boolean> pinMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageService.pinMessage(messageId, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{messageId}/pin")
    @Operation(summary = "取消置顶", description = "取消消息的置顶状态")
    public Result<Boolean> unpinMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageService.unpinMessage(messageId, userId);
        return Result.success(result);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索消息", description = "在群组中搜索消息")
    public Result<PageResult<ChatMessageVO>> searchMessages(
            @Parameter(description = "群组ID") @RequestParam @NotBlank String groupId,
            @Parameter(description = "关键词") @RequestParam @NotBlank String keyword,
            @Parameter(description = "消息类型") @RequestParam(required = false) Integer messageType,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize) {
        String userId = UserContext.getUserId();
        PageResult<ChatMessageVO> result = chatMessageService.searchMessages(keyword, groupId, messageType, userId, pageNum, pageSize, null);
        return Result.success(result);
    }

    @GetMapping("/{messageId}/statistics")
    @Operation(summary = "消息统计", description = "获取消息统计信息")
    public Result<Object> getMessageStatistics(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        String userId = UserContext.getUserId();
        Object statistics = chatMessageService.getMessageStatistics(messageId, userId);
        return Result.success(statistics);
    }

    @PostMapping("/batch-delete")
    @Operation(summary = "批量删除消息", description = "批量删除指定的消息")
    public Result<Boolean> batchDeleteMessages(@RequestBody @NotEmpty List<String> messageIds) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageService.batchDeleteMessages(messageIds, userId);
        return Result.success(result);
    }

    @GetMapping("/export")
    @Operation(summary = "导出消息", description = "导出群组消息记录")
    public Result<String> exportMessages(
            @Parameter(description = "群组ID") @RequestParam @NotBlank String groupId,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime,
            @Parameter(description = "导出格式") @RequestParam(defaultValue = "excel") String format) {
        String userId = UserContext.getUserId();
        String exportUrl = chatMessageService.exportMessages(groupId, startTime, endTime, format, userId);
        return Result.success(exportUrl);
    }
}
